package com.winit.schedule.task.tracker.remoting;

import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;
import java.util.Map;

import com.winit.schedule.core.protocol.Protocol.RequestCode;
import com.winit.schedule.remoting.exception.RemotingCommandException;
import com.winit.schedule.remoting.netty.NettyRequestProcessor;
import com.winit.schedule.remoting.protocol.RemotingCommand;
import com.winit.schedule.remoting.protocol.RemotingProtos;

public class RemotingDispatcher extends AbstractProcessor {

    private static final Map<RequestCode, NettyRequestProcessor> processors = new HashMap<RequestCode, NettyRequestProcessor>();

    public RemotingDispatcher(RemotingClientService remotingService){
        super(remotingService);

    }

    @Override
    public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request)
                                                                                             throws RemotingCommandException {
        RequestCode code = RequestCode.valueOf(request.getCode());
        NettyRequestProcessor processor = processors.get(code);
        if (processor == null) {
            return RemotingCommand.createResponseCommand(RemotingProtos.ResponseCode.REQUEST_CODE_NOT_SUPPORTED.code(),
                "request code not supported!");
        }
        return processor.processRequest(ctx, request);
    }
}
